package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-03-23
 * Time: 11:16
 */
// 点击查看全文后, 跳转到指定博客得详情页

@WebServlet("/detail")
public class BlogDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 约定为请求为: GET:/blog_detail?blogId = ?
        // 此处请求与之气那得博客列表中得请求不一样, 此处带有 queryString 即带有 blogId
        // 如果存在该博客 就返回指定博客得详情页面, 反之返回博客列表

        // 约定响应为: HTTP/1.1 200 OK
        // {
        //   blogId : 1, title: '这是第 ? 篇博客', content: '完整博客全文', postTIme : "发布时间", userId: 1
        // }

        ObjectMapper objectMapper = new ObjectMapper();
        // 获取 blogId 判定是否存在
        String blogId = req.getParameter("blogId");
        if(blogId == null) {
            System.out.println("blogId: " + blogId + " 对应博客不存在!");
            resp.sendError(404);
        } else {
            // 通过 blogId 获取指定博客内容
            BlogDao blogDao = new BlogDao();
            Blog blog = blogDao.selectById(Integer.parseInt(blogId));
            // 将 blog java对象转为 json 格式字符串
            String respJson = objectMapper.writeValueAsString(blog);
            // 设置响应格式
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respJson);
        }

    }
}
